package org.td.engine.entity.tower;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import org.td.engine.TowerPickFilter;
import org.td.engine.combat.Weapon;
import org.td.engine.entity.Entity;
import org.td.engine.entity.EntityClass;
import org.td.engine.entity.EntitySprite;

public class Turret extends Entity{

    private Tower owner;

    private float relX;
    private float relY;
    private float rotation;
    private Weapon weapon;

    private Entity target;

    private EntitySprite sprite;
    private TurretClass turretClass;

    public Turret(Tower owner, TurretClass turretClass, float x, float y) {
        super(owner.getEntityEnvironment(), turretClass) ;
        this.relX = x;
        this.relY = y;
        this.owner = owner;
        this.turretClass = turretClass;

        sprite = new EntitySprite(turretClass.getTextureFile());
    }

    public void setWeapon(Weapon weapon) {
        this.weapon = weapon;
    }

    public void update(float time) {
        weapon.update(time);
        target = getNewTarget();
        if (target != null) {
            Vector2 radVector = new Vector2(target.getX() - (relX + owner.getCenterX()), target.getY() - (relY + owner.getCenterY()));
            radVector = radVector.nor();

            float angle = (float)Math.toDegrees(Math.atan2(radVector.y, radVector.x));
            sprite.setRotation(angle);

            weapon.fire(target);

        }
    }

    @Override
    public EntityClass getEntityClass() {
        return turretClass;
    }

    public void render(SpriteBatch batch) {
        sprite.render(batch, relX + owner.getCenterX(), relY + owner.getCenterY(), true);
    }

    public Entity getNewTarget() {
        Entity newTarget = owner.getEntityEnvironment().pickNearest(owner.getCenterX(), owner.getCenterY(), new TowerPickFilter(owner.getCenterX(), owner.getCenterY(), weapon.getWeaponClass().getRange()));
        return newTarget;
    }

    public float getX() {
        return owner.getCenterX() + relX;
    }

    public float getY() {
        return owner.getCenterY() + relY;
    }
}
